package com.wanpinghui.wphlibrary.model.business;

import com.wanpinghui.wphlibrary.common.IWPHApi;
import com.wanpinghui.wphlibrary.model.business.bean.CommentBean;
import com.wanpinghui.wphlibrary.model.business.bean.DynamicBean;
import com.wanpinghui.wphlibrary.model.business.bean.DynamicPageData;
import com.wanpinghui.wphlibrary.model.business.bean.SaveDynamic;
import com.wanpinghui.wphlibrary.model.business.bean.ThumbUpBean;
import com.wanpinghui.wphlibrary.model.user.bean.AreaBean;
import com.wanpinghui.wphlibrary.photovideo.bean.BaseUrlBean;
import com.wanpinghui.wphlibrary.photovideo.bean.UploadFileBean;
import com.yunshl.yunshllibrary.utils.TextUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit.Network;
import retrofit.callback.YRequestCallback;
import retrofit.callback.YunShlAction;
import retrofit.callback.YunShlResult;
import retrofit2.Call;
import retrofit2.Response;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


/**
 * Created by tg596 on 2018/1/27.
 */

public class BusinessServiceImp implements BusinessService {
    private int uploadSize;
    private ArrayList<BaseUrlBean> imgList;

    @Override
    public void getAreaEngineerInfo(final YRequestCallback<List<AreaBean>> callback) {
        Network.getYSApi(IWPHApi.class).getAreaEngineerInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<List<AreaBean>>>() {
                    @Override
                    public void call(YunShlResult<List<AreaBean>> result) {
                        if (callback != null){
                            if (result.isSuccess()){
                                callback.onSuccess(result.body);
                            }else {
                                callback.onFailed(0,result.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));

    }

    public void commentDynamic(int dynamicId, int userId, String content, final YRequestCallback<List<CommentBean>> callback) {
        if (TextUtil.isNotEmpty(content.trim())) {
            Map<String, Object> map = new HashMap<>();
            map.put("personal_dynamic_id", dynamicId);
            if (userId != 0) {
                map.put("reply_to", userId);
            }
            map.put("content", content);
            Network.getYSApi(IWPHApi.class).addReply(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<YunShlResult<List<CommentBean>>>() {
                        @Override
                        public void call(YunShlResult<List<CommentBean>> result) {
                            if (callback != null){
                                if (result.isSuccess()){
                                    callback.onSuccess(result.body);
                                }else {
                                    callback.onFailed(result.status,result.msg);
                                }
                            }
                        }
                    },new YunShlAction<Throwable>(callback));
        }else {
            if (callback != null) {
                callback.onFailed(0,"请输入评论内容");
            }
        }

    }

    @Override
    public void addOrCancelLike(int dynamicId, boolean like, final YRequestCallback<List<ThumbUpBean>> callback) {
        Map<String, Object> map = new HashMap<>();
        map.put("personal_dynamic_id", dynamicId);
        map.put("type", like?1:2);
        Network.getYSApi(IWPHApi.class).addOrCancelLike(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<List<ThumbUpBean>>>() {
                    @Override
                    public void call(YunShlResult<List<ThumbUpBean>> result) {
                        if (callback != null){
                            if (result.isSuccess()){
                                callback.onSuccess(result.body);
                            }else {
                                callback.onFailed(result.status,result.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }

    @Override
    public void saveDynamic(SaveDynamic dynamic, final YRequestCallback<Object> callback) {
        Network.getYSApi(IWPHApi.class).saveDynamic(dynamic)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<Object>>() {
                    @Override
                    public void call(YunShlResult<Object> result) {
                        if (callback != null){
                            if (result.isSuccess()){
                                callback.onSuccess(result.body);
                            }else {
                                callback.onFailed(0,result.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }

    @Override
    public void uploadPictures(final List<UploadFileBean> uploadFileBeanList, final YRequestCallback<List<BaseUrlBean>> callback) {
        uploadSize = 0;
        if (imgList == null) {
            imgList = new ArrayList<>();
        }
        imgList.clear();
        uploadFile(uploadFileBeanList, callback);
    }

    private Subscription subscription;

    private void uploadFile(final List<UploadFileBean> uploadFileBeanList, final YRequestCallback<List<BaseUrlBean>> callback) {

        subscription  = Observable.from(uploadFileBeanList)
                .map(new Func1<UploadFileBean, BaseUrlBean>() {
                    @Override
                    public BaseUrlBean call(UploadFileBean uploadFileBean) {
                        if (uploadFileBean.getPath().startsWith("http")) {
                            BaseUrlBean baseUrlBean = new BaseUrlBean();
                            baseUrlBean.setUrl(uploadFileBean.getPath());
                            baseUrlBean.setWidth(uploadFileBean.getWidth());
                            baseUrlBean.setHeight(uploadFileBean.getHeight());
                            baseUrlBean.setType_(uploadFileBean.getType());
                            return  baseUrlBean;
                        } else {
                            File file = new File(uploadFileBean.getPath());
                            if (file.exists()) {
                                final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                                        .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file))
                                        .build();
                                Call call = Network.getApi(IWPHApi.class)
                                        .pictures(requestBody);
                                try {
                                    Response<YunShlResult<BaseUrlBean>> response = call.execute();
                                    YunShlResult<BaseUrlBean> result = response.body();
                                    if (result.status == 200) {
                                        result.body.setType_(uploadFileBean.getType());

                                        result.body.setHeight(uploadFileBean.getHeight());
                                        result.body.setWidth(uploadFileBean.getWidth());

                                        return result.body;
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                return null;
                            } else {
                                return null;
                            }
                        }
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseUrlBean>() {
                    @Override
                    public void onCompleted() {
                        if (callback != null) {
                            if (imgList.size() == uploadFileBeanList.size()) {
                                callback.onSuccess(imgList);
                            }else {
                                callback.onFailed(0,"上");
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (subscription != null && subscription.isUnsubscribed()) {
                            subscription.unsubscribe();
                        }
                        if (callback != null) {
                            callback.onFailed(0,"上");
                        }
                    }

                    @Override
                    public void onNext(BaseUrlBean baseUrlBean) {
                        if (baseUrlBean == null) {
                            if (subscription != null && subscription.isUnsubscribed()) {
                                subscription.unsubscribe();
                            }
                        }else {
                            imgList.add(baseUrlBean);
                        }
                    }
                });

    }


    @Override
    public void searchLatelyDynamicList(long user_id, final YRequestCallback<List<DynamicBean>> callback) {
        Network.getYSApi(IWPHApi.class)
                .searchLatelyDynamicList(user_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<List<DynamicBean>>>() {
                    @Override
                    public void call(YunShlResult<List<DynamicBean>> result) {
                        if (callback != null){
                            if (result.isSuccess()){
                                callback.onSuccess(result.body);
                            }else {
                                callback.onFailed(0,result.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }

    @Override
    public void getAllDynamic(long lastTime, final YRequestCallback<DynamicPageData> callback) {
        Network.getYSApi(IWPHApi.class).searchAllDynamicList(20,lastTime==0?null:lastTime)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<DynamicPageData>>() {
                    @Override
                    public void call(YunShlResult<DynamicPageData> result) {
                        if (callback != null){
                            if (result.isSuccess()){
                                callback.onSuccess(result.body);
                            }else {
                                callback.onFailed(result.status,result.msg);
                            }
                        }
                    }
                }, new YunShlAction<Throwable>(callback));
    }

    @Override
    public void getPersonDynamic(int userId, long lastTime, final YRequestCallback<DynamicPageData> callback) {
        Network.getYSApi(IWPHApi.class).searchUserDynamicList(userId,20,lastTime==0?null:lastTime)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<DynamicPageData>>() {
                    @Override
                    public void call(YunShlResult<DynamicPageData> result) {
                        if (callback != null){
                            if (result.isSuccess()){
                                callback.onSuccess(result.body);
                            }else {
                                callback.onFailed(0,result.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }

    @Override
    public void deleteComment(int commentId, final YRequestCallback<List<CommentBean>> callback) {
        Network.getYSApi(IWPHApi.class)
                .deleteComment(commentId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<List<CommentBean>>>() {
                    @Override
                    public void call(YunShlResult<List<CommentBean>> result) {
                        if (callback != null){
                            if (result.isSuccess()){
                                callback.onSuccess(result.body);
                            }else {
                                callback.onFailed(result.status,result.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }

    @Override
    public void deleteDynamic(int dynamicId, final YRequestCallback<Object> callback) {
        Network.getYSApi(IWPHApi.class)
                .deleteDynamic(dynamicId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<Object>>() {
                    @Override
                    public void call(YunShlResult<Object> result) {
                        if (callback != null){
                            if (result.isSuccess()){
                                callback.onSuccess(result.body);
                            }else {
                                callback.onFailed(result.status,result.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }
}
